//
//  FlatToolBar.m
//  AppFrameWork
//
//  Created by Le Anh Tai on 7/19/13.
//  Copyright (c) 2013 Le Anh Tai. All rights reserved.
//

#import "FlatToolBarView.h"

@implementation FlatToolBarView

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self)
    {
        _toolbarItems = [[NSMutableArray alloc] init];
    }
    
    return self;
}

- (FlatToolBarViewItem*)addToolbarItemWithTitle:(NSString *)title icon:(NSString *)icon
{
    FlatToolBarViewItem *item = [FlatToolBarViewItem toolbarItemWithTitle:title
                                                                     icon:icon
                                                          highlightHeight:2];
    item.tag = _toolbarItems.count;
    [_toolbarItems addObject:item];
    [self addSubview:item];
    
    [item addTarget:self action:@selector(itemPressed:) forControlEvents:UIControlEventTouchUpInside];
    
    [self arrangeItems];
    
    //default selectedItem
    if (_toolbarItems.count == 1)
    {
        [self setSelectedItem:item];
    }
    
    return item;
}

- (void)setSelectedItem:(FlatToolBarViewItem *)selectedItem
{
    [_selectedItem setSelected:NO];
    [selectedItem setSelected:YES];
    _selectedItem = selectedItem;
}

- (NSInteger)selectedIndex
{
    if (_selectedItem)
    {
        return _selectedItem.tag;
    }
    
    return -1;
}

- (void)setSelectedIndex:(NSInteger)selectedIndex
{
    if (selectedIndex < _toolbarItems.count)
    {
        [self setSelectedItem:[_toolbarItems objectAtIndex:selectedIndex]];
    }
}

- (void)itemPressed:(FlatToolBarViewItem*)sender
{
    [self setSelectedItem:sender];
    
    if ([_delegate respondsToSelector:@selector(flatToolBar:didSelectedAtIndex:)])
    {
        [_delegate flatToolBar:self didSelectedAtIndex:_selectedItem.tag];
    }
}

- (void)arrangeItems
{
    [self setFrame:self.frame];
}

- (void)setFrame:(CGRect)frame
{
    [super setFrame:frame];
    
    NSInteger totalItem = _toolbarItems.count;
    if (totalItem > 0)
    {
        CGFloat itemWidth = self.width/totalItem;
        for (int i = 0; i < totalItem; i++)
        {
            FlatToolBarViewItem *item = [_toolbarItems objectAtIndex:i];
            [item setFrame:CGRectMake(itemWidth*i, 0, itemWidth, self.height)];
        }
    }
}

@end
